package com.xieyong.leetcode;

import java.util.ArrayList;
import java.util.List;

public class Leetcode2014 {
    public static void main(String[] args) {
        Leetcode2311 leetcode2311 = new Leetcode2311();
        String s = "letsleetcode";
        int k = 2;
        int i = leetcode2311.longestSubsequence(s, k);
        System.out.println(i);
    }

    private char[] chars;

    private int k;

    private int[] cnt;

    private String ans;

    public String longestSubsequenceRepeatedK(String s, int k) {
        this.k = k;
        this.ans = "";
        this.chars = s.toCharArray();
        this.cnt = new int[26];
        for (char c : chars) cnt[c - 'a']++;
        List<Character> list = new ArrayList<>();
        for (char i = 'z'; i >= 'a'; i--) if (cnt[i - 'a'] >= k) list.add(i);
        dfs(list, new StringBuilder(), cnt.clone(), s.length() / k);
        return ans;
    }

    private void dfs(List<Character> list, StringBuilder path, int[] cnt, int maxlen) {
        if (path.length() > maxlen) return;
        if (path.length() > 0 && !check(path.toString())) return;
        if (path.length() > ans.length()) ans = path.toString();
        for (Character c : list) {
            if ((this.cnt[c - 'a'] - cnt[c - 'a']) * k > this.cnt[c - 'a']) continue;
            path.append(c);
            cnt[c - 'a']--;
            dfs(list, path, cnt, maxlen);
            path.deleteCharAt(path.length() - 1);
            cnt[c - 'a']++;
        }
    }

    private boolean check(String s) {
        int i = 0, j = 0, cnt = 0;
        while (j < chars.length) {
            if (chars[j++] == s.charAt(i)) i++;
            if (i >= s.length()) {
                if (++cnt >= k) return true;
                i = 0;
            }
        }
        return false;
    }
}
